const Snowflake = require('../Snowflake')
const db = require('../SQLHelper')

function Entity(table,attr){
  this.table = table
  this.attr = attr || {}
  this.getAttrs = function(){
    let rc = []
    for(let key in this.attr) rc.push(key)
    return rc
  }
  //新增验证参数
  this.validate = function(data){
    let keys = [],values = []
    data.id = data.id || Snowflake()
    for(let key in this.attr){
      keys.push(key)
      let value = data[key] || ''
      if(this.attr[key].required && !value) return { errorMsg:this.attr[key].label + '不能为空' }
      value = '"' + value + '"'
      values.push(value)
    }
    return {
      keys,
      values
    }
  }

  //按id查询详情
  this.getById = async function(id){
    let res = await db.query(`select * from ${ this.table } where id = ${id};`)
    return res[0] || { errorMsg:'no data' }
  }

  //分页查询
  this.selectPage = async function(sql,pageNum,pageSize){
    pageNum = pageNum || 1
    pageSize = pageSize || 10
    sql = sql.replace(/;$/,'')
    let rows = await db.query(`${sql} limit ${pageSize} offset ${ pageSize * (pageNum - 1) }`)
    let total = await db.query(sql.replace(/^select(.+)from/i,'select count(*) as count from'))
    return {
      rows,
      total:total[0].count
    }
  }
    
  //新增
  this.insert = async function(data){
    let validate = this.validate(data)
    if(validate.errorMsg) {
      return { errorMsg:validate.errorMsg }
    }
    //插入数据
    return await db.query(`INSERT INTO ${ this.table } (${ validate.keys.join(',') }) VALUES (${ validate.values.join(',') });`)
  }

  //修改
  this.updateById = async function(data){
    //验证参数
    if(!data.id) return { errorMsg:'请传入ID' }
    let updates = []
    for(let key in this.attr){
      if(data[key] === undefined || data[key] === null) continue
      if(key == 'id') continue
      let value = data[key]
      value = '"' + value + '"'
      updates.push(`${key}=${value}`)
    }
    //插入数据
    return await db.query(`UPDATE ${this.table} set ${updates.join(',')} where id = ${data.id};`)
  }

  //删除
  this.deleteById = async function(id){
    //验证参数
    if(!id) return { errorMsg:'请传入ID' }
    //插入数据
    return await db.query(`DELETE FROM ${ this.table } WHERE id = ${ id };`)
  }
}

var fs = require('fs')
var files = fs.readdirSync('./entity')

module.exports = (function(){
  let entities = {}
  for(var i = 0; i < files.length; i ++){
    if(files[i] != 'index.js' && /\.js$/.test(files[i])) {
      let tabelName = files[i].split('.')[0]
      let entity = require('./' + files[i])
      entities[tabelName] = new Entity(tabelName,entity)
      try{
        let mapper = require('../mapper/' + tabelName)
        mapper.call(entities[tabelName])
      }catch(e){}
    }
  }
  return entities
})()